import {
  BrowserRouter as Router,
  Routes,
  Route,
  useNavigate,
  useLocation,
  To,
} from "react-router-dom";
import { Menu } from "antd";
import routes, { RoutesItem } from "./router";
import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
import "./App.scss";
import { useSelector, useDispatch } from "react-redux";
import { RootState, AppDispatch } from "./store";
import { menuUnfoldChannge } from "./store/modules/layoutSlice";

const AppMenu = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const menuUnfold = useSelector(
    (state: RootState) => state.layoutSlice.menuUnfold
  );
  const handleMenuClick = (e: { key: To }) => {
    navigate(e.key); // 菜单 key 即为路径，直接跳转
  };
  // 返回菜单目录
  const filterOutHiddenRoutes = () => {
    const filterRoutes = (route: any[]) => {
      const filtered = route.filter((r) => !r.hidden);
      filtered.forEach((r) => {
        if (r.children && r.children.length > 0) {
          r.children = filterRoutes(r.children);
        }
      });
      return filtered;
    };

    let arr = filterRoutes(routes);
    return arr;
  };
  return (
    <Menu
      theme="dark"
      mode="inline"
      inlineCollapsed={!menuUnfold}
      onClick={handleMenuClick}
      selectedKeys={[location.pathname]} // 设置选中状态
      items={filterOutHiddenRoutes()}
    />
  );
};

const App = () => {
  const menuUnfold = useSelector(
    (state: RootState) => state.layoutSlice.menuUnfold
  );
  const dispatch = useDispatch<AppDispatch>();
  //  遍历路由
  const routesCom = () => {
    const flogArr: RoutesItem[] = [];
    const arrfun = (arr: any[]) => {
      arr.forEach((item: RoutesItem) => {
        flogArr.push(item);
        item.children && arrfun(item.children);
      });
    };
    arrfun(routes);
    return flogArr;
  };
  return (
    <Router>
      <div className="app-content">
        <div
          className="left-side"
          style={{ width: menuUnfold ? "200px" : "80px" }}
        >
          <div className="logo">L O G O</div>
          <AppMenu />
        </div>
        <div className="right-box">
          <div className="right-header">
            <span
              className="menu-unfold"
              onClick={() => dispatch(menuUnfoldChannge())}
            >
              {menuUnfold ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />}
            </span>
          </div>
          <div className="right-content">
            <Routes>
              {routesCom().map((route) => (
                <Route
                  key={route.key}
                  path={route.path}
                  element={route.component}
                />
              ))}
            </Routes>
          </div>
        </div>
      </div>
    </Router>
  );
};

export default App;
